#include "Xtable.h"

extern int Xtable_init(Xtable this)
{
	int i;

	this = malloc(sizeof(struct XD_TABLE));
	for(i = 0; i <= 4; i++)
	{
		this -> table[i] = malloc(sizeof(Xnode));
		this -> table[i] -> nxt = NULL;
		this -> table[i] -> uplnk = malloc(sizeof(Xnode*));
		*this -> table[i] -> uplnk = NULL;
		if(i != 0)
		{
			this -> table[i] -> dnlnk =malloc(sizeof(Xnode*));
			*this -> table[i] -> dnlnk = NULL;
		}
	}
	this -> dim = {0, 0};
	return 0;
}

extern int Xtable_clear(Xtable this)
{
	int i;
	Xnode *pTemp;

	for(i = 0; i <= 4; i++)
	{
		pTemp = this -> table[i];
		while(pTemp != NULL)
		{
			pTemp = pTemp -> nxt;
			free(pTemp -> bak -> uplnk);
			if(i != 0) free(pTemp -> bak -> dnlnk);
			free(pTemp -> bak);
		}
	}
	free(this);
	return 0;
}


extern int Xtable_add_point(Xtable this, const double *coord)
{
	Xnode *pTemp;

	pTemp = this -> *table;
	while(pTemp -> nxt != NULL) pTemp = pTemp -> nxt;
	pTemp -> nxt = malloc(sizeof(Xnode));
	pTemp = pTemp -> nxt;
	pTemp -> nxt = NULL;
	pTemp -> uplnk = malloc(sizeof(Xnode*));
	*pTemp -> uplnk = NULL;
	pTemp -> coord = coord;
	return 0;
}

extern int Xtable_add_struct(Xtable this, const usigned int dim, const unsigned int *dnlnk_id)
{
	Xnode *pTemp, sub_pTemp;

	pTemp = this -> table[dim];
	while(pTemp -> nxt != NULL) pTemp = pTemp -> nxt;
	pTemp -> nxt = malloc(sizeof(Xnode));
	pTemp = pTemp -> nxt;
	pTemp -> nxt = NULL;
	pTemp -> uplnk = malloc(sizeof(Xnode*));
	*pTemp -> uplnk = NULL;
	sub_pTemp = this -> table[dim];
	while(sub_pTemp -> nxt != NULL)
	{
	}
}

extern int Xtable_delete(Xtable this, const unsigned int dim, const unsigned int target_id)
{
	int i;
	Xnode *pTemp, **Iterator, **sub_Iterator,**new_uplnk;

	pTemp = this -> table[dim] -> nxt;
	while(pTemp != NULL)
	{
		if(pTemp -> id == target_id)
		{
			Iterator = pTemp -> uplnk;
			while(*Iterator != NULL)
			{
				Xtable_delete(this, dim + 1, (*Iterator) -> id);
				Iterator ++;
			}
			free(pTemp -> uplnk);
			if(dim != 0)
			{
				Iterator = pTemp -> dnlnk;
				while(Iterator != NULL)
				{
					sub_Iterator = (*Iterator) -> uplnk;
					i = 1;
					new_uplnk = malloc(sizeof(Xnode));
					while(*sub_Iterator != NULL)
					{
						if(*sub_Iterator != pTemp)
						{
							i ++;
							new_uplnk = realloc(new_uplnk, sizeof(Xnode**) * i);
							new_uplnk[i - 2] = *sub_Iterator;
						}
						sub_Iterator ++;
					}
					new_uplnk[i - 1] = NULL;
					free((*Iterator) -> uplnk);
					(*Iterator) -> uplnk = new_uplnk;
					Iterator ++;
				}
				free(pTemp -> dnlnk);
			}
			pTemp -> bak -> nxt = pTemp -> nxt;
			pTemp -> nxt -> bak = pTemp -> bak;
			free(pTemp);
			return 0;
		}
		pTemp = pTemp -> nxt;
	}
	return 2;
}
